package org.zecontech.extraplus.datagen.loot;

import net.minecraft.advancements.critereon.StatePropertiesPredicate;
import net.minecraft.core.HolderLookup;
import net.minecraft.data.loot.BlockLootSubProvider;
import net.minecraft.world.flag.FeatureFlags;
import net.minecraft.world.item.Item;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.CropBlock;
import net.minecraft.world.level.storage.loot.predicates.LootItemBlockStatePropertyCondition;
import net.minecraft.world.level.storage.loot.predicates.LootItemCondition;
import org.zecontech.extraplus.init.ModBlocks;
import org.zecontech.extraplus.init.ModItems;

import java.util.Set;

/**
 * 模组方块掉落数据文件提供者
 */
public class ModBlockLoot extends BlockLootSubProvider {

    protected ModBlockLoot(HolderLookup.Provider registries) {
        super(Set.of(), FeatureFlags.DEFAULT_FLAGS, registries);
    }

    /**
     * 添加掉落数据
     */
    @Override
    protected void generate() {
        ModBlocks.BLOCKS.getEntries().forEach(blockDeferredHolder -> {
            var id = blockDeferredHolder.getId();
            if (!id.toString().contains("ore") && !(blockDeferredHolder.get() instanceof CropBlock)) {
                dropSelf(blockDeferredHolder.get());
            }
        });
        addOreDrop(ModBlocks.RUBY_ORE.get(), ModItems.RUBY.get());
        addOreDrop(ModBlocks.AMBER_ORE.get(), ModItems.AMBER.get());
        addCropDropWithSeed(ModBlocks.ONION.get(), ModBlocks.ONION.get().asItem(),
                ModBlocks.ONION.get().asItem());
        addCropDropWithSeed(ModBlocks.ETHEREAL_STRAWBERRY.get(),
                ModBlocks.ETHEREAL_STRAWBERRY.get().asItem(),
                ModBlocks.ETHEREAL_STRAWBERRY.get().asItem());
        addCropDropWithSeed(ModBlocks.PEPPER.get(),
                ModBlocks.PEPPER.get().asItem(),
                ModBlocks.PEPPER.get().asItem());
    }

    /**
     * 添加作物掉落数据
     * @param block 作物方块
     * @param item 作物
     * @param seed 作物种子
     */
    private void addCropDropWithSeed(Block block, Item item, Item seed) {
        LootItemCondition.Builder builder =
                LootItemBlockStatePropertyCondition.hasBlockStateProperties(block)
                        .setProperties(StatePropertiesPredicate.Builder.properties()
                                .hasProperty(CropBlock.AGE, 7));
        add(block, this.createCropDrops(block, item, seed, builder));
    }

    /**
     * 添加矿石掉落数据
     * @param block 矿石方块
     * @param item 矿石
     */
    private void addOreDrop(Block block, Item item) {
        add(block, createOreDrop(block, item));
    }

    /**
     * 获取已知的方块
     * @return 已知的方块
     */
    @Override
    protected Iterable<Block> getKnownBlocks() {
        return ModBlocks.BLOCKS.getEntries()
                .stream()
                .map(e -> (Block) e.value())
                .toList();
    }

}
